package com.startx.http.filter;

import static com.startx.core.system.HttpParser.getHttpParam;

import java.util.Objects;

import com.startx.core.filter.StartxFilter;
import com.startx.core.filter.define.Filter;
import com.startx.core.netty.response.http.JsonResponse;
import com.startx.core.system.model.AccessResult;
import com.startx.core.system.model.AccessTarget;
import com.startx.core.system.param.HttpContext;
import com.startx.core.system.param.HttpParam;
import com.startx.http.system.annotation.RequireLogin;
import com.startx.http.system.cache.TokenCache;
import com.startx.http.system.exception.MiniException;
import com.startx.http.system.tool.ResponseBuilder;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

@Filter
public class AuthFilter implements StartxFilter {

	@Override
	public boolean doBefore(HttpContext context, FullHttpRequest request, AccessTarget target) throws Exception {
		try {
			HttpParam param = getHttpParam(context.getContext(), request);
			
			String token = param.getParam("token");
			if(!Objects.isNull(token)) {
				//延长有效期
				TokenCache.delayExpire(token);
			}
			
			//跳过非必登录流程
			if(!target.getMethod().isAnnotationPresent(RequireLogin.class)){
				return true;
			}
			
			//校验登录
			TokenCache.checkLogin(token);
		} catch (MiniException e) {
			FullHttpResponse fhr = JsonResponse.getResponse(
					HttpResponseStatus.OK,
					ResponseBuilder.build(e.getCode()));
			
			ChannelFuture f = context.getContext().channel().writeAndFlush(fhr);
			f.addListener(ChannelFutureListener.CLOSE);
			
			return false;
		}
		
		return true;
	}

	@Override
	public boolean doAfter(HttpContext ctx, AccessResult result) throws Exception {
		return true;
	}
}
